<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <link rel="stylesheet" href="styles/style.css">
        <link rel="stylesheet" href="styles/theme/atom-one-dark.css">
        <title>例子22-ES6/7常用语法介绍</title>
    </head>
    <body>
        <pre>
            <code>
                // 例子22

                // 1、复制数组
                // ES5
                var a1 = [1, 2];
                var a2 = a1.concat();
                console.log(a2); // [1, 2]

                // ES6
                const a1 = [1, 2];
                const a2 = [...a1]; // 或者const [...a2] = a1;
                console.log(a2); // [1, 2]

                //--------------------------------------------------------------------------

                // 2、合并数组
                // ES5
                var a1 = ['a', 'b'];
                var a2 = ['c'];
                var a3 = ['d', 'e'];

                a1.concat(a2, a3); // ["a", "b", "c", "d", "e"]

                // ES6
                const a1 = ['a', 'b'];
                const a2 = ['c'];
                const a3 = ['d', 'e'];
                [...a1, ...a2, ...a3]; // ["a", "b", "c", "d", "e"]

                //--------------------------------------------------------------------------

                // 3、与解构赋值结合使用(注意扩展运算符用于解构赋值时只能写在最后一个位置)
                let [first, ...rest] = [1, 2, 3, 4, 5];
                console.log(first, rest); // 1 [2, 3, 4, 5]

                [first, ...middle, last] = [1, 2, 3, 4, 5]; // Uncaught SyntaxError: Rest element must be last element

                //--------------------------------------------------------------------------

                // 4、字符串处理
                'x\uD83D\uDE80y'.length // 4, 错误，这种写法JS会将4个字节的Unicode字符识别为2个字符
                [...'x\uD83D\uDE80y'].length // 3，正确

                // 字符串长度的正确处理
                function length(str) {
                    return [...str].length;
                }
                length('x\uD83D\uDE80y'); // 3
            </code>
        </pre>
        <script src="scripts/libs/highlight.pack.js"></script>
        <script src="scripts/22.js"></script>
        <script>
            hljs.initHighlightingOnLoad();
        </script>
    </body>
</html>